package com.simple.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simple.entity.entity.UserDayCost;
import com.simple.entity.vo.CostStat;
import com.simple.mapper.UserDayCostMapper;
import com.simple.util.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @desc
 * @Author Simple
 * @Date 2025/7/8 21:56
 **/
@Slf4j
@Service
public class UserDayCostService extends ServiceImpl<UserDayCostMapper, UserDayCost> {

    public CostStat costStatByUser(Long userId, boolean isFree) {
        CostStat result = new CostStat();

        int today = LocalDateTimeUtil.getIntDay(LocalDateTime.now());
        int start = LocalDateTimeUtil.getIntDay(LocalDateTime.now().withDayOfMonth(1));
        int end = LocalDateTimeUtil.getIntDay(LocalDateTime.now().plusMonths(1).withDayOfMonth(1).minusDays(1));

        List<UserDayCost> userDayCostList = this.lambdaQuery()
                .eq(UserDayCost::getUserId, userId)
                .between(UserDayCost::getDay, start, end)
                .eq(UserDayCost::getIsFree, isFree)
                .list();
        for (UserDayCost userDayCost : userDayCostList) {
            // todo 这里需要测试会不会空指针
            result.setTextTokenCostByMonth(result.getTextTokenCostByMonth() + userDayCost.getTokens());
            result.setTextRequestTimesByMonth(result.getTextRequestTimesByMonth() + userDayCost.getRequestTimes());
            result.setDrawTimesByMonth(result.getDrawTimesByMonth() + userDayCost.getDrawTimes());

            if (userDayCost.getDay() == today) {
                result.setTextTokenCostByDay(userDayCost.getTokens());
                result.setTextRequestTimesByDay(userDayCost.getRequestTimes());
                result.setDrawTimesByDay(userDayCost.getDrawTimes());
            }
            result.setFree(userDayCost.getIsFree());
        }
        return result;

    }
}
